#include "airpower.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <string.h>

// 外部引用UI组件
extern lv_obj_t *ui_powervalue;
extern lv_obj_t *ui_airvalue;

// 静态变量
static pthread_t airpower_thread;
static int running = 0;
static int current_power = 100;
static time_t last_power_update;
static int last_aqi = 25;  // 记录上一次AQI值，用于波动计算

/**
 * 生成25±3范围内的随机AQI值（确保每次波动）
 */
static int get_random_aqi(void)
{
    static int seed_initialized = 0;
    if (!seed_initialized) {
        srand(time(NULL));
        seed_initialized = 1;
    }
    
    int new_aqi;
    // 确保新值与旧值不同，且在22-28范围内
    do {
        new_aqi = 25 + ((rand() % 7) - 3);  // -3到+3的随机偏移
    } while (new_aqi == last_aqi);
    
    last_aqi = new_aqi;
    return new_aqi;
}

/**
 * 更新电量值（10秒降1%）
 */
static void update_power_value(void)
{
    time_t current_time = time(NULL);
    double elapsed = difftime(current_time, last_power_update);
    
    // 每10秒减少1%电量
    if (elapsed >= 10 && current_power > 0) {
        current_power--;
        last_power_update = current_time;
    }
}

/**
 * 数据更新线程函数
 */
static void *airpower_update_thread(void *arg)
{
    char text_buf[16];
    last_power_update = time(NULL);
    
    while (running) {
        // 更新电量
        update_power_value();
        if (ui_powervalue != NULL) {
            snprintf(text_buf, sizeof(text_buf), "%d%%", current_power);
            lv_label_set_text(ui_powervalue, text_buf);
        }
        
        // 更新空气质量（每2秒波动一次）
        if (ui_airvalue != NULL) {
            int aqi = get_random_aqi();
            snprintf(text_buf, sizeof(text_buf), "%dAQI", aqi);
            lv_label_set_text(ui_airvalue, text_buf);
        }
        
        // 2秒刷新一次AQI，同时检查电量更新
        sleep(2);
    }
    
    return NULL;
}

void airpower_init(void)
{
    current_power = 100;
    last_aqi = 25;
    if (ui_powervalue != NULL) {
        lv_label_set_text(ui_powervalue, "100%");
    }
    if (ui_airvalue != NULL) {
        lv_label_set_text(ui_airvalue, "25AQI");
    }
}

int airpower_start(void)
{
    if (running) {
        return 0;
    }
    
    running = 1;
    int ret = pthread_create(&airpower_thread, NULL, 
                           airpower_update_thread, NULL);
    if (ret != 0) {
        running = 0;
        return -1;
    }
    
    return 0;
}

void airpower_stop(void)
{
    if (running) {
        running = 0;
        pthread_join(airpower_thread, NULL);
    }
}

void airpower_deinit(void)
{
    airpower_stop();
}
    